<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/8/12
 * Time: 10:25
 */

namespace App\Imports;

use App\Models\Company;
use App\Models\DriverOthers;
use App\Models\Drivers;
use App\Models\ServiceType;
use App\Models\User;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class DriverOtherImport implements ToCollection
{
    public function collection(Collection $row)
    {

        $data = $row->toArray();  //接收的对象数据装换为数组
        unset($data[0]);           //去除excel表头
        DB::beginTransaction();  //开启事务
        try {
            //遍历数组
            foreach ($data as $row) {

                //验证司机姓名长度
                if (mb_strlen($row[0]) > 10) {
                    throw new Exception('司机姓名过长');
                }

                //验证手机号格式是否正确
                if (!validateChinaPhoneNumber($row[1])) {
                    throw new Exception("{$row[1]}手机格式不对");
                }

                //查询公司是否存在返回id值
                if (!$company_id = Company::where('name', $row[2])->value('id')) {
                    throw new Exception("{$row[2]}公司不存在");
                }
                //查询类型是否存在返回id值
                if (!$type_id = ServiceType::where('name', $row[3])->value('id')) {
                    throw new Exception("{$row[3]}类型不存在");
                }
                //创建或者查找用户
                $user = User::firstOrCreate(
                    ['phone' => $row[1]]
                );


                //创建或者查找司机
                $driver = Drivers::firstOrCreate(
                    ['phone' => $row[1]],
                    [
                        'real_name' => trim($row[0]),
                        'company_id' => $company_id,
                        'user_id' => $user->id,
                        'status' => 2
                    ]
                );
                DriverOthers::query()->firstOrCreate(
                    ['driver_id' => $driver->id],
                    [
                        'company_id' => $company_id,
                        'status' => 2,
                        'city' => 0,
                        'identity_photo' => [],
                        'licence_photo' => [],
                        'auditor_id' => 1,
                        'province' => 0
                    ]
                );
                //更新司机姓名
                $dr = Drivers::where('phone', '=', $row[1])->value('id');
                Drivers::query()->where('id', $dr)->update(['real_name' => $row[0]]);
            }
            DB::commit();  //提交事务
        } catch (Exception $e) {
            DB::rollBack(); //回滚事务
            return_bob($e->getMessage());
        }
    }
}